<?php
namespace App\Component;
use EasySwoole\Component\Singleton;
use EasySwoole\EasySwoole\Config;
use Qiniu\Auth;
use Qiniu\Storage\UploadManager;


class Qiniu
{

    use Singleton;

    private $accessKey;
    private $secretKey;
    private $bucket;
    private $uploadManager;
    private $domain;

    public function __construct($config=[])
    {
        $qiniuConfig = Config::getInstance()->getConf('QINIUCONFIG');
        $config = array_merge($qiniuConfig ?? [], $config);
        $this->accessKey = $config['accessKey'];
        $this->secretKey = $config['secretKey'];
        $this->bucket = $config['bucket'];
        $this->domain = $config['domain'];
        $this->uploadManager = new UploadManager();
    }

    /**
     * 鉴权
     * @return Auth
     */
    public function getAuth()
    {
        return new Auth($this->accessKey, $this->secretKey);
    }

    /**
     * 获取上传token
     * @return String
     */
    public function getToken():String
    {
        return $this->getAuth()->uploadToken($this->bucket);
    }

    /**
     * 执行上传
     * @param $file
     * @param string $newFileName
     * @param string $ext
     */
    public function upload($file, $newFileName)
    {
        list($ret, $err) = $this->uploadManager->putFile($this->getToken(), $newFileName, $file);
        if ($err !== null){
            return false;
        }else {
            return $this->domain.$ret['key'];
        }
    }
    
    /**
     * 执行上传
     * @param $file
     * @param string $newFileName
     * @param string $ext
     */
    public function uploadUrl($file_path, $newFileName)
    {
        $file = file_get_contents($file_path);
        list($ret, $err) = $this->uploadManager->put($this->getToken(), $newFileName, $file);
        if ($err !== null){
            return false;
        }else {
            return $this->domain.$ret['key'];
        }
    }

}